package cate.game.pvp.throne.data.rival;

import cate.common.table.d.GDThrone;
import cate.common.util.XT;
import cate.game.play.part.PlaySide;
import cate.game.pvp.throne.data.TBGroupData;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@NoteClass(value = "王座争霸对手库数据", detail = "来自段位赛")
@Slf4j
public class TBRivalData extends TBGroupData {

	@NoteField("真人对手库")
	public List<TBRivalPs> list;

	@Override
	public void init() {
		if (list == null) {
			list = new ArrayList<>();
		}
	}

	public void clear(){
		list.clear();
		log.info("[王座争霸]{}号组选拔赛对手库清除完毕", levelGroup);
	}

	public void sort(){
		list.sort(Comparator.comparingLong(a->-a.playSide.snapshot.base.power));
	}

	public void setRivals(List<PlaySide> playSides) {
		if (XT.isNotBlank(playSides)) {
			list = playSides.stream().sorted(Comparator.comparingLong(p -> -p.snapshot.base.power)).
					limit(GDThrone.TRIAL_RIVAL_MAX).map(p -> new TBRivalPs(levelGroup, p)).collect(Collectors.toList());
			log.info("[王座争霸]{}号组选拔赛对手库设置完毕共有{}个对手", levelGroup, list.size());
		} else {
			log.info("[王座争霸]{}号组选拔赛对手库设置完毕共有0个对手", levelGroup);
		}
	}

	public PlaySide randomPlaySide(String roleUid, double start, double end) {
		int indexStart = (int) start - 1;
		int indexEnd = (int) end - 1;
		if (indexStart < 0 || indexEnd < 0) {
			return null;
		}
		List<PlaySide> playSides = new ArrayList<>();
		for (int i = indexStart; i < Math.min(list.size(), indexEnd); i++) {
			PlaySide playSide = list.get(i).playSide;
			if (StringUtils.equals(playSide.snapshot.uid, roleUid)) {
				continue;
			}
			playSides.add(playSide);
		}
		if (XT.isNotBlank(playSides)) {
			return playSides.get(XT.randomIndex(playSides.size()));
		}
		return null;
	}
}
